﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using log4net.Appender;
using System.Windows.Forms;

namespace Collector
{
    public enum logType
    {
        /// <summary>
        /// 应用程序出现严重错误(程序已经无法正常运行) Blue
        /// </summary>
        FATAL,
        /// <summary>
        /// 应用程序进行调试的信息 Black
        /// </summary>
        DEBUG,
        /// <summary>
        /// 应用程序运行过程的信息  Green
        /// </summary>
        INFO,
        /// <summary>
        /// 应用程序可能存在潜在错误的信息 Orange
        /// </summary>
        WARN,
        /// <summary>
        /// 应用程序出现错误(程序仍可继续运行) Red
        /// </summary>
        ERROR,
    }

    public enum LogMsgType
    {
        /// <summary>
        /// 应用程序出现严重错误(程序已经无法正常运行)
        /// </summary>
        FATAL,
        /// <summary>
        /// 应用程序进行调试的信息
        /// </summary>
        DEBUG,
        /// <summary>
        /// 应用程序运行过程的信息
        /// </summary>
        INFO,
        /// <summary>
        /// 应用程序可能存在潜在错误的信息
        /// </summary>
        WARN,
        /// <summary>
        /// 应用程序出现错误(程序仍可继续运行)
        /// </summary>
        ERROR,
        /// <summary>
        /// 作为单独消息输出 不存log的一个标志
        /// </summary>
        MSG
    }

    public delegate void LogWrite(string str, logType msgtype);
    public static class Log
    {
        /// <summary>
        /// 返回源码文件,所执行的函数名，以及所在的行号
        /// </summary>
        /// <returns></returns>
        public static string GetRunCodeInfo()
        {
            string filename = "";
            string funname = "";
            int linenum = 0;
            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, true);
            var obj = st.GetFrame(st.FrameCount > 1 ? 1 : 0);
            linenum = obj.GetFileLineNumber();
            filename = Path.GetFileName(obj.GetFileName());

            funname = obj.GetMethod().Name;
            return string.Format("[{0},{1},{2}]", filename, funname, linenum);
        }
        public static event LogWrite OnLogWrite;
        // 实例
        public static log4net.ILog Instance { get; private set; }
        // 构造方法
        static Log()
        {
            FileInfo fi = new System.IO.FileInfo("log4net.config".AppPath());
            log4net.Config.XmlConfigurator.ConfigureAndWatch(fi);
            // 取log4net.config的root默认引用的Appender
            Instance = log4net.LogManager.GetLogger(string.Empty);
        }
        public static void Debug(string format, params object[] args)
        {
            try
            {
                //var ss = GetRunCodeInfo();
                //format = ss + ":" + format;
                Log.Instance.DebugFormat(format, args);
                if (Log.OnLogWrite != null)
                {
                    var _format = string.Format(format, args);
                    Log.OnLogWrite(_format, logType.DEBUG);
                }
            }
            catch
            {

            }
        }

        public static void Debug(string format)
        {
            try
            {
                //var ss = GetRunCodeInfo();
                //format = ss + ":" + format;
                Log.Instance.Debug(format);
                if (Log.OnLogWrite != null)
                {
                    Log.OnLogWrite(format, logType.DEBUG);
                }
            }
            catch
            {

            }
        }

        public static void Info(string format, params object[] args)
        {
            Log.Instance.InfoFormat(format, args);
            if (Log.OnLogWrite != null)
            {
                var _format = string.Format(format, args);
                Log.OnLogWrite(_format, logType.INFO);
            }
        }

        public static void Warn(string format, params object[] args)
        {
            Log.Instance.WarnFormat(format, args);
            if (Log.OnLogWrite != null)
            {
                var _format = string.Format(format, args);
                Log.OnLogWrite(_format, logType.WARN);
            }
        }

        public static void Warn(Exception ex)
        {
            Log.Instance.WarnFormat(ex.Message, ex);
            if (Log.OnLogWrite != null)
            {
                Log.OnLogWrite(ex.Message, logType.WARN);
            }
        }

        public static void Error(string format, params object[] args)
        {
            Log.Instance.ErrorFormat(format, args);
        }

        public static void Error(Exception ex)
        {
            Log.Instance.Error(ex.Message, ex);
            if (Log.OnLogWrite != null)
            {
                Log.OnLogWrite(ex.Message, logType.ERROR);
            }
        }

        public static void Fatal(string format, params object[] args)
        {
            Log.Instance.FatalFormat(format, args);
        }

        public static void Fatal(Exception ex)
        {
            Log.Instance.FatalFormat(ex.Message, ex);
        }

        public static string AppPath(this string input)
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, input);
        }

        public static object lockObject = new object();
        /// <summary>
        /// 写入csv
        /// </summary>
        /// <param name="result">写入内容 ----单元格内容，单元格内容-----</param>
        public static void WriteCsv(string result)
        {
            try
            {
                lock (lockObject)
                {
                    string path = "";//保存路径
                    string fileName = "";//
                    string Datedate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//年月日小时分钟秒
                    string CsvData = "";
                    string mmHgInfo = "";

                    path = Application.StartupPath + "\\log\\FullFunctionTest";

                    if (!FileConfig.getmmHgListInfo("mmHg_pPressureList", out mmHgInfo))
                    {
                        Log.Debug(string.Format("{0} 脉压集合列表初始化失败", mmHgInfo), LogMsgType.ERROR);
                        return;
                    }
                    List<int> mmHgListInfo = mmHgInfo.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToList();
                    string info = "脉压值average(mmHg),脉压值airPreDiff(mmHg),脉压值FrontValue(mmHg),脉压值LastValue(mmHg),";
                    CsvData = "SN,初始脉压(mbar),气泵频率(KHz),气泵序列号,程序版本号,气压零飘(Pa),初始气压(Pa)," +
                        string.Format("0-{0}mmHg加压时间(S),", mmHgListInfo[0]) + info +
                        string.Format("{0}-{1}mmHg加压时间(S),", mmHgListInfo[0], mmHgListInfo[1]) + info +
                        string.Format("{0}-{1}mmHg加压时间(S),", mmHgListInfo[1], mmHgListInfo[2]) + info +
                        "泄压时间(S),测试结果 Pass/Fail,测试时间" + "\t\n";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    fileName = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv";//文件名
                    if (!File.Exists(fileName))
                    {
                        StreamWriter sw = new StreamWriter(fileName, true, Encoding.UTF8);
                        sw.Write(CsvData);
                        sw.Close();
                    }
                    StreamWriter swl = new StreamWriter(fileName, true, Encoding.UTF8);
                    string str = result + Datedate + "\t\n";
                    swl.Write(str);
                    swl.Close();
                }
            }
            catch (Exception ex)
            {
                Log.Debug(string.Format("WriteCsv CaughtException :{0}", ex.Message));
            }
        }

    }


    //  public static class MyLog
    //  {
    //      public static event LogWrite OnLogWrite;
    //      // 实例
    //      //public static log4net.ILog Instance { get; private set; } loggers 
    //      private static Dictionary<string, log4net.ILog> loggers = new Dictionary<string, log4net.ILog>();
    //      // 构造方法
    //      static MyLog()
    //      {
    ////          log4net.Config.BasicConfigurator.Configure(

    ////new log4net.Appender.FileAppender(

    ////   new log4net.Layout.PatternLayout("%d

    ////     [%t]%-5p %c [%x] - %m%n"),"testfile.log"));

    //          //log4net.Config.BasicConfigurator.Configure(new log4net.Appender.RollingFileAppender() {
    //          // Layout = 
    //          //});


    //          //FileInfo fi = new System.IO.FileInfo("log4net.config".GetAppPath());
    //          //log4net.Config.XmlConfigurator.ConfigureAndWatch(fi);
    //          //// 取log4net.config的root默认引用的Appender
    //          //var Instance = log4net.LogManager.GetLogger(string.Empty);
    //          //loggers.Add("DEFAULT", Instance);

    //          var repository = log4net.LogManager.GetRepository();

    //          //var appenders = repository.GetAppenders();
    //          //var targetApder = appenders.First(p => p.Name == "ShowSqlAppender") as log4net.Appender.RollingFileAppender;
    //          //targetApder.File = "D:/Media/Logs/Cache/";
    //          //targetApder.ActivateOptions();
    //      }


    //      private static log4net.ILog GetInstance(string logger)
    //      {
    //          if (!loggers.ContainsKey(logger))
    //          {
    //              var appender = CreateRollingFileAppender(logger);
    //              appender.ActivateOptions();
    //              loggers.Add(logger, log4net.LogManager.GetLogger(logger));

    //              ((log4net.Repository.Hierarchy.Logger)loggers[logger].Logger).AddAppender(appender);
    //          }
    //          return loggers[logger];
    //      }
    //      private static log4net.Appender.RollingFileAppender CreateRollingFileAppender(string appname)
    //      {
    //          var layout = new log4net.Layout.PatternLayout
    //          {
    //              ConversionPattern = "%date [%thread] %-5level %logger [%property{NDC}] - %message%newline",
    //              Header = "---------------------------header-------------------------------newline",
    //              Footer = "---------------------------footer-------------------------------newline"
    //          };
    //          layout.ActivateOptions();

    //          return new log4net.Appender.RollingFileAppender
    //          {
    //              Name = appname,
    //              AppendToFile = true,
    //              DatePattern = "yyyyMMdd",
    //              MaximumFileSize = "1MB",
    //              MaxSizeRollBackups = 10,
    //              RollingStyle = RollingFileAppender.RollingMode.Composite,
    //              File = "..\\Log\\123_log.txt",
    //              Layout = layout

    //          };
    //      }
    //      public static void Debug(string appname, string format, params object[] args)
    //      {
    //          GetInstance(appname).DebugFormat(format, args);
    //          if (MyLog.OnLogWrite != null)
    //          {
    //              MyLog.OnLogWrite(format, logType.DEBUG);
    //          }
    //      }

    //      public static void Debug(string appname, string format)
    //      {
    //          try
    //          {
    //              GetInstance(appname).Debug(format);

    //              var repository = log4net.LogManager.GetRepository();
    //              var appenders = repository.GetAppenders();
    //              var ls = appenders.ToList();
    //              Console.WriteLine(ls.Count);
    //              if (MyLog.OnLogWrite != null)
    //              {
    //                  MyLog.OnLogWrite(format, logType.DEBUG);
    //              }
    //          }
    //          catch
    //          {

    //          }
    //      }

    //      public static void Info(string appname, string format, params object[] args)
    //      {
    //          GetInstance(appname).InfoFormat(format, args);
    //          if (MyLog.OnLogWrite != null)
    //          {
    //              MyLog.OnLogWrite(format, logType.INFO);
    //          }
    //      }

    //      public static void Warn(string appname, string format, params object[] args)
    //      {
    //          GetInstance(appname).WarnFormat(format, args);
    //          if (MyLog.OnLogWrite != null)
    //          {
    //              MyLog.OnLogWrite(format, logType.WARN);
    //          }
    //      }

    //      public static void Warn(string appname, Exception ex)
    //      {
    //          GetInstance(appname).WarnFormat(ex.Message, ex);
    //          if (MyLog.OnLogWrite != null)
    //          {
    //              MyLog.OnLogWrite(ex.Message, logType.WARN);
    //          }
    //      }

    //      public static void Error(string appname, string format, params object[] args)
    //      {
    //          GetInstance(appname).ErrorFormat(format, args);
    //      }

    //      public static void Error(string appname, Exception ex)
    //      {
    //          GetInstance(appname).Error(ex.Message, ex);
    //          if (MyLog.OnLogWrite != null)
    //          {
    //              MyLog.OnLogWrite(ex.Message, logType.ERROR);
    //          }
    //      }

    //      public static void Fatal(string appname, string format, params object[] args)
    //      {
    //          GetInstance(appname).FatalFormat(format, args);
    //      }

    //      public static void Fatal(string appname, Exception ex)
    //      {
    //          GetInstance(appname).FatalFormat(ex.Message, ex);
    //      }

    //      public static string GetAppPath(this string input)
    //      {
    //          return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, input);
    //      }
    //  }
}
